package everyday.apr;

import everyday.apr.support.Node;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 429. N 叉树的层序遍历
 */
public class Day8 {
    public static void main(String[] args) {
        System.out.println(levelOrder(new Node(1, List.of(new Node(3,
                List.of(new Node(5), new Node(6))), new Node(2), new Node(4)))));
    }

    /**
     * 利用队列实现的bfs
     */
    public static List<List<Integer>> levelOrder(Node root) {
        if (root == null) return List.of();
        List<List<Integer>> res = new ArrayList<>();
        Queue<Node> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node curr = queue.poll();
                assert curr != null;
                list.add(curr.val);
                if (curr.children != null)queue.addAll(curr.children);
            }
            res.add(list);
        }

        return res;
    }
}
